from pathlib import Path
import pickle
import json

data = {"name": "jackie", "age": 10}

pickle_file_path = Path(__file__).parent / "data.pickle"
json_file_path = Path(__file__).parent / "data.json"
json_file_bin_path = Path(__file__).parent / "json.pickle"

with open(pickle_file_path, "wb") as pickfile:
    # dump  把data转换成字节流写入到文件
    pickle.dump(data, pickfile)

with open(pickle_file_path, "rb") as pickfile:

    data = pickle.load(pickfile)
    print(type(data), "data=", data)


# json的使用
with open(json_file_path, "w", encoding="utf-8") as jsonfile:
    # dump
    json.dump(data, jsonfile, ensure_ascii=True, indent=4)

# 使用json把数据保存为二进制数据
with open(json_file_bin_path, "wb") as binfile:
    # dump
    try:
        json.dump(data, binfile)
    except IOError as e:
        print("写入错误=", e)


with open(json_file_path, "r", encoding="utf-8") as jsonfile:
    # dump
    load_content = json.load(jsonfile)

    print("类型=", type(load_content), "data=", load_content)


with open(json_file_bin_path, "rb") as binfile:
    # dump
    try:
        load_content = json.load(binfile)
    except IOError as e:
        print("读取错误=", e)
